/*
 * @Author: wanli wanliofficial@aliyun.com
 * @Date: 2025-05-13 11:26:01
 * @LastEditors: wanli wanliofficial@aliyun.com
 * @LastEditTime: 2025-05-13 12:00:32
 * @FilePath: \locust4j\src\benchmark\java\com\github\myzhan\locust4j\CollectionsTest\MyBenchmark.java
 * @Description: 
 * 
 * Copyright (c) 2025 by wanli email: wanliofficial@aliyun.com, All Rights Reserved. 
 */
package com.github.myzhan.locust4j.collectionstest;

import java.util.concurrent.TimeUnit;
import java.util.Collection;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.results.RunResult;

@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
public class MyBenchmark {
    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.NANOSECONDS)
    @Threads(4) // 4 个线程并发执行
    public void testMethod() {
        // 你的测试代码
        int sum = 0;
        for (int i = 0; i < 1000; i++) {
            sum += i;
        }
        System.out.println("sum is " + sum);

        // return sum;
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(MyBenchmark.class.getSimpleName()).forks(1).build();
        Runner runner = new Runner(opt);
        Collection<RunResult> results = runner.run();
        // 处理结果
        for (RunResult result : results) {
            String benchmarkName = result.getParams().getBenchmark(); // 测试方法名
            double score = result.getPrimaryResult().getScore(); // 主要结果（如平均耗时）
            String unit = result.getPrimaryResult().getScoreUnit(); // 单位
            double error = result.getPrimaryResult().getStatistics().getStandardDeviation(); // 标准差
            System.out.printf("Benchmark: %s, Score: %.3f %s, Error: ±%.3f%n", benchmarkName, score, unit, error);
        }
    }
}